
#include <Python.h>
#include <pygobject.h>
#include <pygtk/pygtk.h>

#include "modTimer.h"

static PyObject *timer_callback = NULL;
static PyTypeObject *PyGObject_Type=NULL;    

PyObject *RunTimer(PyObject *self, PyObject *args)
{
	int preinsp;
if (PyArg_ParseTuple(args, "i", &preinsp))
		run(preinsp);

	return Py_BuildValue("i",0);
}

PyObject *RunTimerStackmat(PyObject *self, PyObject *args)
{
	run_stackmat();

	return Py_BuildValue("i",0);
}

PyObject *InitTimer(PyObject *self, PyObject *args)
{
	PyGObject *widget;
	if (PyArg_ParseTuple(args, "O!", PyGObject_Type,&widget))
	{
		init(GTK_WIDGET(widget->obj));
	}
	return Py_BuildValue("i",0);
}


static PyObject *TimerCallback(PyObject *dummy, PyObject *args)
{
	PyObject *result = NULL;
	PyObject *temp;

	if (PyArg_ParseTuple(args, "O:set_callback", &temp))
	{
		if (!PyCallable_Check(temp))
		{
			PyErr_SetString(PyExc_TypeError, "parameter must be callable");
			return NULL;
        	}
		Py_XINCREF(temp);
		Py_XDECREF(timer_callback);
		timer_callback = temp;
		Py_INCREF(Py_None);
		result = Py_None;
	}
	return result;
}

void _run_callback(double _time)
{
	if (!PyCallable_Check(timer_callback)) return;
	PyObject *arglist;
	PyObject *result;
	arglist = Py_BuildValue("(d)", _time);
	result = PyEval_CallObject(timer_callback, arglist);
	Py_DECREF(arglist);
	Py_DECREF(result);
}



PyMethodDef methods[] = {
  {"init", InitTimer, METH_VARARGS},
  {"timerRun", RunTimer, METH_VARARGS},
  {"timerRunStackmat", RunTimerStackmat, METH_VARARGS},
  {"timerCallback", TimerCallback, METH_VARARGS},
      {NULL, NULL},
    };

void initcubeass()
      {
        (void)Py_InitModule("cubeass", methods);
	PyObject *module;
	init_pygobject();
	init_pygtk();
	module = PyImport_ImportModule("gobject");
	if (module)
	{
		PyGObject_Type =
			(PyTypeObject*)PyObject_GetAttrString(module, "GObject");
		Py_DECREF(module);
	}
}
